package com.example.usbfileutils.bylibaums

import android.util.Log
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class FileCopyExecutors{

    private val executors: ExecutorService = Executors.newSingleThreadExecutor()
    private val copyTaskQueue: MutableList<FileCopyTaskByLibaums> = ArrayList()
    private lateinit var countDownNumber: CountDownLatch

    companion object {
        val TAG = "FileCopyExecutors"
    }

    fun addTask(copyTask: FileCopyTaskByLibaums) {
        copyTaskQueue.add(copyTask)
    }

    fun start() {

        if (copyTaskQueue.size == 0) {
            Log.d(TAG, "copyTaskQueue is empty")
            return
        }

        countDownNumber = CountDownLatch(copyTaskQueue.size)

        Log.d(TAG, "start copyfile Task, all task size is ${copyTaskQueue.size}")

        copyTaskQueue.forEach {
            it.countDownLatch = countDownNumber

            executors.submit(it)
        }
    }

    fun stop() {
        Log.d(TAG, "stop the executor")

        executors.shutdown()
    }

}